import { IDecorator } from '../../types/decorator'

const Get = (_target: any, name: string, descriptor: IDecorator) => {
  const original = descriptor.value

  if (typeof original === 'function') {
    descriptor.value = async function (...args: any[]) {
      const [ctx] = args
      const params = ctx.query

      ctx.body = {
        ResponseMetadata: {
          Action: `${name}`,
        },
        Result: {},
      }

      try {
        const res = await original.apply(this, [ctx, params])
        ctx.body.Result = res
      } catch (err: any) {
        ctx.body.ResponseMetadata.Error = {
          Code: 500,
          Msg: err.toString(),
        }
      }
      ctx.status = 200
    }
  }
  return descriptor
}
const Post = (_target: any, name: string, descriptor: IDecorator) => {
  const original = descriptor.value

  if (typeof original === 'function') {
    descriptor.value = async function (...args: any[]) {
      const [ctx] = args
      const params = ctx.request.body

      ctx.body = {
        ResponseMetadata: {
          Action: `${name}`,
        },
        Result: {},
      }

      try {
        ctx.body.Result = await original.apply(this, [ctx, params])
      } catch (err: any) {
        if (err !== null) {
          ctx.body.ResponseMetadata.Error = {
            Code: 500,
            Msg: err.toString(),
          }
        }
      }

      ctx.status = 200
    }
  }

  return descriptor
}

const exp = {
  Get,
  Post,
}

export default exp
export { Get, Post }
